// 初始化 user 状态模块，设置状态值初始化从本地存储获取，页面刷新不丢失数据
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { stat } from 'fs'
export interface IUserState {
    loginState: boolean
    adminname: string
    token: string
    role: number
    checkedkeys: any[]
}
const initialState = {
    loginState: localStorage.getItem('loginState') === 'true',
    adminname: localStorage.getItem('adminname') || '',
    token: localStorage.getItem('token') || '',
    role: Number(localStorage.getItem('role')),
    checkedkeys: JSON.parse(localStorage.getItem('checkedkeys')!)
}as IUserState
export const userslice = createSlice({
    name:'user',
    initialState,
    reducers:{
        changeLoginState(state,action:PayloadAction<boolean>){
            localStorage.setItem('loginState',action.payload.toString())
            state.loginState = action.payload
        },
        changeAdminName(state,action:PayloadAction<string>){
            localStorage.setItem('adminname',action.payload)
            state.adminname = action.payload
        },
        changeToken(state,action:PayloadAction<string>){
            localStorage.setItem('token',action.payload)
            state.token = action.payload
        },
        changeRole(state,action:PayloadAction<number>){
            localStorage.setItem('role',action.payload + '')
            state.role = action.payload
        },
        changeCheckedkeys(state,action:PayloadAction<any[]>){
            localStorage.setItem('checkedkeys',JSON.stringify(action.payload))
            state.checkedkeys = action.payload
        }
    }
})
// 快捷导出方法，方便直接调用
export const {changeLoginState,changeAdminName,changeToken,changeRole,changeCheckedkeys} = userslice.actions
export default userslice.reducer